import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { ChatRecord } from '@/services/contact-chat'
import { type ExternalTransfer } from '@/services/contact-types'
import { ContactType, type Contact, type BaseContact } from '@/services/contacts'
import { type QywxInfo } from '@/services/qywxs'

export type ChatOwner = Pick<QywxInfo, 'avatar' | 'friendlyName' | 'friendlyFullName'>

/**
 * 返回聊天所属企业微信信息
 */
type BaseContactWithTransfer = Pick<BaseContact, 'ownerWxid'> & {
  transfer?: Pick<ExternalTransfer, 'ownerName'>
}

export function useOwner(contact: BaseContactWithTransfer): ChatOwner {
  const [qywxs] = useStreams(services.qywxs.alives)
  return contact.transfer
    ? {
        avatar: '',
        friendlyName: contact.transfer.ownerName,
        friendlyFullName: contact.transfer.ownerName,
      }
    : qywxs.get(contact.ownerWxid) ?? {
        avatar: '',
        friendlyName: `wxid:${contact.ownerWxid}`,
        friendlyFullName: `wxid:${contact.ownerWxid}`,
      }
}

/**
 * 返回聊天内容发送者的信息
 */
interface Sender {
  name: string
  avatar: string
}

export function getSender(params: {
  record: ChatRecord
  contact: Pick<Contact, 'type' | 'name' | 'avatar'>
  owner: ChatOwner
  groupMembers?: BaseContact[] | Map<string, BaseContact>
}): Sender {
  const { record, contact, owner, groupMembers } = params
  if (record.isSend) {
    return { name: owner.friendlyName, avatar: owner.avatar }
  } else if (contact.type === ContactType.group) {
    // 先尝试从传入的 members 中获取信息，未提供或未找到则使用聊天记录里的信息
    let member: Sender | undefined
    if (Array.isArray(groupMembers))
      member = groupMembers.find(m => m.id === record.groupSenderWxid)
    else if (groupMembers) member = groupMembers.get(record.groupSenderWxid)
    return member ?? { name: record.groupSenderName, avatar: '' }
  } else {
    return { name: contact.name, avatar: contact.avatar }
  }
}
